<?php
class SequenceModel extends CI_Model
{
    // Create record with command: db.{collection}.insert({"_id": "{name}", "value": new NumberLong(1)});
    const collection = 'sequence';

    public function  __construct()
    {
        parent::__construct();        
    }

    public function getSequence($name)
    {
        if(empty($name)) return false;
        
        $rs = $this->mongo_db->where(array('_id' => $name))->getOne(self::collection);
        if(isset($rs['value'])) {
            return $rs['value'];
        }

        // Return
        return false;
    }

    public function increment($name)
    {
        if(empty($name)) return false;
        
        $params = array (
            'findandmodify' => self::collection,
            'query' => array('_id' => $name),
            'update' => array('$inc' => array('value' => 1)),
            'new' => TRUE
        );
        // Return
        return $this->mongo_db->command($params);
    }

    public function decrement($name)
    {
        if(empty($name)) return false;

        $params = array (
            'findandmodify' => self::collection,
            'query' => array('_id' => $name),
            'update' => array('$inc' => array('value' => -1)),
            'new' => TRUE
        );
        // Return
        return $this->mongo_db->command($params);
    }
}
?>